<template>
  <inline-Modal
    :visible="visible"
    :title="title"
    @ok="$emit('ok')"
    @cancel="
      () => {
        $emit('cancel');
      }
    "
  >
    <!-- <a-button
      type="primary"
      class="get-user-info-button"
      @click="userInfoSource.visible = true"
    >
      获取用户信息
    </a-button> -->
    <a-spin :spinning="loading">
      <a-form :form="form">
        <a-card title="账号信息" :bordered="false" style="width: 100%">
          <div class="headText">初始化密码为用户账号</div>
          <a-row>
            <a-col span="12">
              <a-form-item
                label="用户账号"
                :labelCol="labelCol"
                :wrapperCol="wrapperCol"
              >
                <a-input
                  placeholder="请输入用户账号"
                  v-decorator="[
                    'userNameId',
                    {
                      rules: [
                        {
                          required: true,
                          message: '请输入用户账号！',
                        },
                      ],
                    },
                  ]"
                />
              </a-form-item>
            </a-col>
            <a-col span="12">
              <a-form-item
                label="用户姓名"
                :labelCol="labelCol"
                :wrapperCol="wrapperCol"
              >
                <a-input
                  placeholder="请输入用户姓名"
                  v-decorator="[
                    'userName',
                    {
                      rules: [
                        {
                          required: true,
                          min: 1,
                          message: '请输入用户姓名！',
                        },
                      ],
                    },
                  ]"
                />
              </a-form-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col span="12">
              <a-form-item
                label="集团短号"
                :labelCol="labelCol"
                :wrapperCol="wrapperCol"
              >
                <a-input
                  :maxLength="6"
                  v-decorator="[
                    'userTelephone',
                    {
                      rules: [
                        {
                          required: false,
                          message: '请输入集团短号!',
                        },
                        {
                          pattern: /^\d{6}$/,
                          maxLength: 11,
                          message: '请输入正确的集团短号！',
                        },
                      ],
                    },
                  ]"
                  placeholder="请输入集团短号"
                />
              </a-form-item>
            </a-col>
            <a-col span="12">
              <a-form-item
                label="手机号码"
                :labelCol="labelCol"
                :wrapperCol="wrapperCol"
              >
                <a-input
                  placeholder="请输入手机号码"
                  v-decorator="[
                    'userCellphone',
                    {
                      rules: [
                        {
                          required: true,
                          message: '请输入手机号码!',
                        },
                        {
                          pattern: /^[1][3,4,5,6,7,8,9][0-9]{9}$/,
                          maxLength: 11,
                          message: '请输入正确的手机号码！',
                        },
                      ],
                    },
                  ]"
                />
              </a-form-item>
            </a-col>
          </a-row>

          <a-row>
            <a-col span="12">
              <a-form-item
                label="所属单位"
                :labelCol="labelCol"
                :wrapperCol="wrapperCol"
              >
                <!-- <t-dict-select-tag
                  type="select"
                  dictCode="affiliatedUnit"
                  placeholder="请选择所属单位"
                  v-decorator="[
                    'affiliatedUnit',
                    {
                      rules: [{ required: true, message: '请选择所属单位！' }],
                    },
                  ]"
                /> -->
                <!-- @change="unitChange($event)" -->
                <a-tree-select
                  style="width: 100%"
                  :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                  treeNodeFilterProp="title"
                  show-search
                  :tree-data="unitSoucre"
                  placeholder="请选择所属单位"
                  :replaceFields="{
                    children: 'children',
                    title: 'orgName',
                    key: 'uuid',
                    value: 'uuid',
                  }"
                  :maxTagCount="4"
                  v-model="affiliatedUnit"
                  @change="unitChange($event)"
                />
                <a-input
                  v-decorator="[
                    'affiliatedUnit',
                    {
                      rules: [{ required: true, message: '请选择所属单位！' }],
                    },
                  ]"
                  disabled
                  type="hidden"
                />
              </a-form-item>
            </a-col>
            <a-col span="12">
              <a-form-item
                label="所属部门或项目部"
                :labelCol="labelCol"
                :wrapperCol="wrapperCol"
              >
                <!-- :multiple="true" -->
                <depart-popup
                  placeholder="请选择所属组织"
                  v-decorator="[
                    'userOrgId',
                    {
                      rules: [{ required: true, message: '请选择所属组织!' }],
                    },
                  ]"
                  @change="departPopupChange"
                ></depart-popup>
              </a-form-item>
            </a-col>
          </a-row>
          <a-row>
            <!-- mode="multiple" -->
            <!-- <a-col span="12">
              <a-form-item
                label="用户岗位"
                :labelCol="labelCol"
                :wrapperCol="wrapperCol"
              >
                <a-select
                  placeholder="请选择用户岗位"
                  @change="handlePositionChange"
                  v-model="positionArr"
                >
                  <a-select-option
                    v-for="item in positionList"
                    :key="item.uuid"
                  >
                    {{ item.positionText }}
                  </a-select-option>
                </a-select>
                <a-input
                  v-decorator="[
                    'userPosition',
                    {
                      rules: [{ required: true, message: '请选择用户岗位！' }],
                    },
                  ]"
                  disabled
                  type="hidden"
                />
              </a-form-item>
            </a-col> -->
            <a-col span="12">
              <a-form-item
                label="岗位角色"
                :labelCol="labelCol"
                :wrapperCol="wrapperCol"
              >
                <a-tree-select
                  style="width: 100%"
                  :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                  treeNodeFilterProp="title"
                  show-search
                  :tree-data="treeData"
                  tree-checkable
                  placeholder="请选择岗位角色"
                  :treeDefaultExpandedKeys="treeDefaultExpandedKeys"
                  :replaceFields="{
                    children: 'children',
                    title: 'text',
                    key: 'uuid',
                    value: 'uuid',
                  }"
                  :maxTagCount="4"
                  @change="roleChange($event)"
                  v-model="userGroup"
                />

                <a-input
                  v-decorator="[
                    'userGroup',
                    {
                      rules: [{ required: true, message: '请选择岗位角色！' }],
                    },
                  ]"
                  disabled
                  type="hidden"
                />
                <!-- <a-select
                  mode="multiple"
                  placeholder="请选择岗位角色"
                  :defaultValue="authGroupArr"
                  @change="selectUserGroupName"
                >
                  <a-select-option v-for="item in authGroup" :key="item.id">
                    {{ item.roleName }}
                  </a-select-option>
                </a-select>
                <a-input
                  v-decorator="[
                    'userGroup',
                    {
                      rules: [{ required: true, message: '请选择岗位角色！' }],
                    },
                  ]"
                  disabled
                  type="hidden"
                /> -->
                <!-- <a-tree-select
                  :defaultValue="authGroupArr"
                  placeholder="请选择岗位角色"
                  style="width: 100%"
                  :tree-data="authGroup"
                  @change="selectUserGroupName"
                />
                <a-input
                  v-decorator="[
                    'userGroup',
                    {
                      rules: [{ required: true, message: '请选择岗位角色！' }],
                    },
                  ]"
                  disabled
                  type="hidden"
                /> -->
              </a-form-item>
            </a-col>
            <a-col span="12">
              <a-form-item
                label="账号状态"
                :labelCol="labelCol"
                :wrapperCol="wrapperCol"
              >
                <t-dict-select-tag
                  type="select"
                  dictCode="UserInfoStatus"
                  placeholder="请选择账号状态"
                  v-decorator="[
                    'userStatus',
                    {
                      initialValue: 'UserInfoStatus.01',
                      rules: [{ required: true, message: '请选择账号状态！' }],
                    },
                  ]"
                />
              </a-form-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col span="12">
              <a-form-item
                label="锁定状态"
                :labelCol="labelCol"
                :wrapperCol="wrapperCol"
              >
                <t-dict-select-tag
                  type="select"
                  dictCode="UserLock"
                  placeholder="请选择锁定状态"
                  v-decorator="[
                    'userLock',
                    {
                      initialValue: 'UserLock.01',
                      rules: [{ required: true, message: '请选择锁定状态！' }],
                    },
                  ]"
                />
              </a-form-item>
            </a-col>
          </a-row>
        </a-card>
        <a-form-item class="hiddenItem">
          <a-input v-decorator="['uuid']" disabled type="hidden" />
        </a-form-item>
      </a-form>
    </a-spin>

    <!-- 用户信息弹窗 -->
    <t-modal
      title="用户信息"
      :width="1000"
      :visible="userInfoSource.visible"
      wrapClassName="userInfoSource-modal"
      cancelText="关闭"
      :destroyOnClose="true"
      @cancel="userInfoSource.visible = false"
      @ok="handleOk"
    >
      <!--  -->
      <div class="condition-warp">
        <a-input placeholder="请输入姓名" v-model="userInfoSource.userName" />
        <a-input
          placeholder="请输入手机号"
          v-model="userInfoSource.userCellphone"
        />
        <a-button type="primary" icon="search" @click="getUserInfoSource()"
          >查询</a-button
        >
        <a-button icon="redo" @click="resetList()">重置</a-button>
      </div>
      <!--  -->
      <div class="table-container">
        <vxe-table
          ref="xTable"
          height="99%"
          align="center"
          show-overflow
          show-header-overflow
          border="inner"
          :data="userInfoSource.tableData"
          :column-config="{ resizable: true }"
          size="small"
          :loading="userInfoSource.loading"
        >
          <vxe-column type="radio" width="50">
            <template #header>
              <vxe-button mode="text" @click="clearRadioRowEevnt"></vxe-button>
            </template>
          </vxe-column>
          <vxe-column field="name" title="用户账号"> </vxe-column>
          <vxe-column field="trueName" title="用户姓名"> </vxe-column>
          <vxe-column field="phoneNumer" title="手机号码"> </vxe-column>
        </vxe-table>
      </div>
      <!--  -->
      <div class="pager-container">
        <vxe-pager
          size="small"
          background
          :current-page.sync="pager.page"
          :page-size.sync="pager.pageSize"
          :total="pager.total"
          :layouts="['PrevPage', 'JumpNumber', 'NextPage', 'Sizes']"
          :page-sizes="[20, 50, 100, 500]"
          @page-change="paginationChange"
        >
          <template #left>
            <div class="vxe-pager-left-tip-container">
              共<span>{{ pager.total }}</span
              >条
            </div>
          </template>
        </vxe-pager>
      </div>
    </t-modal>
  </inline-Modal>
</template>

<script>
import pick from "lodash.pick";
import TMultiSelectTag from "@/components/TopVUI/dict/TMultiSelectTag";
import TreeSelect from "@/components/TopVUI/custom/TreeSelect";
import { getFilter } from "@/utils/TopVUI";
import DepartPopup from "@/components/TopVUI/custom/DepartPopup";
import { PersonnelPopup } from "@/components";
import ARow from "ant-design-vue/es/grid/Row";
import { TImageUpload, TDictSelectTag } from "@/components";
import { getProTreeSelect } from "@/api/knowledgeBase";
// 表单字段
const fields = [
  "uuid",
  "userName",
  "userNameId",
  "nickName",
  "userSex",
  "userAge",
  "userEmail",
  "userOrgId",
  "affiliatedUnit",
  "userReportsTo",
  "userPosition",
  "userGroup",
  "userEntryTime",
  "userStatus",
  "userLock",
  "userSort",
  "userRemark",
  "userHeadPortrait",
  "userBirthday",
  "userPersonalSignature",
  "userFamilyName",
  "userNativePlace",
  "userTelephone",
  "userCellphone",
  "politicalOutlook",
  "userEducation",
  "idCard",
  "idCardNo",
  "depositBank",
  "bankAccounts",
];
export default {
  props: {
    visible: {
      type: Boolean,
      required: true,
    },
    loading: {
      type: Boolean,
      default: () => false,
    },
    model: {
      type: Object,
      default: () => null,
    },
  },
  components: {
    ARow,
    TMultiSelectTag,
    TreeSelect,
    TImageUpload,
    DepartPopup,
    PersonnelPopup,
    TDictSelectTag,
  },
  data() {
    return {
      userInfoSource: {
        visible: false,
        tableData: [1, 2, 3, 4],
        loading: false,
        userName: "",
        userCellphone: "",
      },
      pager: {
        page: 1,
        pageSize: 20,
        total: 0,
      },
      title: "用户信息",
      labelCol: {
        xs: {
          span: 24,
        },
        sm: {
          span: 4,
        },
      },
      wrapperCol: {
        xs: {
          span: 24,
        },
        sm: {
          span: 20,
        },
      },
      form: this.$form.createForm(this),
      authGroup: [],
      // SHOW_PARENT,
      dataAuth: "",
      urlAuth: {
        // fathersUrl: "/system/authGroup/getListByUserUuid",
        fathersUrl: "/system/sysRole/getListSysRole",
      },
      positionArr: undefined,
      positionList: [],
      authGroupArr: [],
      userPosition: "",
      //角色
      treeData: [],
      userGroup: [],
      treeDefaultExpandedKeys: [],
      //所属单位
      unitSoucre: [],
      affiliatedUnit: undefined,
    };
  },
  computed: {
    userInfoModal() {
      return this.userInfoSource.visible;
    },
  },
  watch: {
    userInfoModal: {
      handler(val) {
        if (val) {
          this.getUserInfoSource();
        } else {
          this.userInfoSource.userName = "";
          this.userInfoSource.userCellphone = "";
          this.userInfoSource.tableData = [];
        }
      },
    },
    visible: {
      handler(val) {
        if (val) {
          this.getData();
          this.userGroup = [];
          this.treeDefaultExpandedKeys = [];
        } else {
          this.userGroup = [];
          this.affiliatedUnit = undefined;
          this.unitSoucre = [];
        }
      },
      immediate: true,
    },
  },
  created() {
    // 获取数据权限
    // this.$post(this.urlAuth.fathersUrl).then((res) => {
    //   if (res.statusCode === 200) {
    //     this.authGroup = res.data;
    //   }
    //   // let authGroup = [];
    //   // let children = [];
    //   // res.forEach((e) => {
    //   //   if (e.pid == 1) {
    //   //     e.title = e.text;
    //   //     e.value = e.id;
    //   //     e.key = e.id;
    //   //     e.children = e.state === "closed" ? [] : "";
    //   //     authGroup.push(e);
    //   //   } else {
    //   //     children.push(e);
    //   //   }
    //   // });
    //   // this.authGroup = getFilter(authGroup, children);
    // });
    // 防止表单未注册
    fields.forEach((v) => this.form.getFieldDecorator(v));
    // 当 model 发生改变时，为表单设置值
    this.$watch("model", () => {
      this.positionArr = undefined;
      //   this.authGroupArr = [];
      if (this.model && JSON.stringify(this.model) != "{}") {
        if (this.model?.userPosition) {
          //   this.positionArr = this.model?.userPosition.split(",");
          this.positionArr = this.model?.userPosition;
          this.userPosition = this.model?.userPosition;
        }
        // this.authGroupArr = this.model?.userGroup.split(",").map(parseFloat);
        //岗位角色
        this.userGroup = this.model.userGroup
          ? this.model.userGroup.split(",")
          : [];
        //所属单位
        this.affiliatedUnit = this.model.affiliatedUnit;
        // this.affiliatedUnit = this.model.affiliatedUnit
        //   ? this.model.affiliatedUnit.split(",")
        //   : [];

        // this.$nextTick(() => {
        //   this.$refs.imageUpload.fileList = [
        //     {
        //       url: this.model["userHeadPortrait"],
        //       uid: "1",
        //       name: "image.png",
        //       status: "done",
        //     },
        //   ];
        //   this.$refs.imageUpload.picUrl = true;
        // });
      }
      this.model && this.form.setFieldsValue(pick(this.model, fields));
    });
  },
  mounted() {},
  methods: {
    getData() {
      this.getUnitData();
      this.getRoleData();
    },
    //查询角色
    getRoleData() {
      this.$post(
        `/mdata/organization/getTreeSysOrganizationAll?type=userBindRole`
      )
        .then((res) => {
          this.treeData = res?.data ?? [];
          this.treeDefaultExpandedKeys = this.treeData.map((v) => v.uuid);
          this.recursiveTree(this.treeData);
        })
        .catch((_) => {
          this.treeData = [];
          this.treeDefaultExpandedKeys = [];
        });
    },
    //查询所属单位
    getUnitData() {
      getProTreeSelect()
        .then((res) => {
          this.unitSoucre = res?.data ?? [];
        })
        .catch((_) => {
          this.unitSoucre = [];
        });
    },
    unitChange() {
      this.form.setFieldsValue({
        affiliatedUnit: this.affiliatedUnit,
      });
    },
    roleChange() {
      this.form.setFieldsValue({
        userGroup: this.userGroup.toString(),
      });
    },
    //处理角色树
    recursiveTree(data = []) {
      data.forEach((item) => {
        this.$set(item, "disabled", true);
        if (item.orgName) {
          item.text = item.orgName;
        }
        if (item.children && item.children.length > 0) {
          this.recursiveTree(item.children);
        }
        if (item.roles && item.roles.length > 0) {
          let array = [];
          item.roles.forEach((v) => {
            array.push({
              text: v.roleName,
              uuid: v.id,
              disabled: false,
            });
          });
          item.children = item.children.concat(array);
        }
      });
    },

    resetList() {
      this.userInfoSource.userName = "";
      this.userInfoSource.userCellphone = "";
      this.getUserInfoSource();
    },

    handleOk() {
      let data = this.$refs.xTable.getRadioRecord();
      if (!data) {
        this.$message.warning("请选择用户！");
        return;
      }
      let { name, trueName, phoneNumer } = data;
      this.form.setFieldsValue({ userNameId: name });
      this.form.setFieldsValue({ userName: trueName });
      this.form.setFieldsValue({ userCellphone: phoneNumer });
      this.userInfoSource.visible = false;
    },

    //查询用户列表
    getUserInfoSource() {
      let { page, pageSize } = this.pager;
      let { userName, userCellphone } = this.userInfoSource;
      this.userInfoSource.loading = true;
      this.$post(`/system/oauser/users?pageNo=${page}&pageSize=${pageSize}`, {
        userName,
        userCellphone,
      })
        .then((res) => {
          let { data } = res;
          this.userInfoSource.tableData = data?.rows ?? [];
          this.pager.total = data?.totalCount ?? 0;
        })
        .catch((_) => {
          this.pager.total = 0;
          this.userInfoSource.tableData = [];
        })
        .finally((_) => {
          this.userInfoSource.loading = false;
        });
    },

    //监听分页切换
    paginationChange({ currentPage, pageSize }) {
      this.pager.page = currentPage;
      this.pager.pageSize = pageSize;
      this.getUserInfoSource();
    },

    clearRadioRowEevnt() {
      this.$refs.xTable.clearRadioRow();
    },

    // 新增编辑
    add(e, data) {
      data.forEach((item) => {
        if (item.id == e.orgId) {
          e.orgName = item.text;
        }
      });
      this.$nextTick(() => {
        let userGroup = e.userGroup ? e.userGroup.split(",") : "";
        this.form.setFieldsValue({
          ...e,
        });
      });
      this.positionList = [];
    },
    edit(e, data) {
      this.add(e, data);
      this.getPositionList(e.userOrgId);
    },
    departPopupChange(value, data) {
      if (value !== this.model.userOrgId || !value) {
        this.positionArr = undefined;
        this.form.setFieldsValue({ userPosition: "" });
        this.userPosition = "";
      }
      this.getPositionList(value);
    },
    //获取岗位列表
    getPositionList(orgId) {
      this.positionList = [];
      const orgIdList = orgId.split(",");
      for (let i = 0; i < orgIdList.length; i++) {
        const element = orgIdList[i];
        let value = {
          orgId: element,
        };
        if (value.orgId) {
          this.$post(
            "/mdata/sysPosition/getSysPositionListByOrgId",
            value
          ).then((res) => {
            if (orgId) {
              //   this.positionArr = this.userPosition
              //     ? this.userPosition.split(",")
              //     : [];
              this.positionArr = this.userPosition
                ? this.userPosition
                : undefined;
              this.form.setFieldsValue({ userPosition: this.userPosition });
            }

            this.positionList = res;

            // res.forEach((item) => {
            //   if (
            //     !this.positionList.some(
            //       (p) => p.positionCode === item.positionCode
            //     )
            //   ) {
            //     this.positionList.push(item);
            //   }
            // });
          });
        }
      }
    },
    // 角色授权
    selectUserGroupName(value, node, extra) {
      this.form.setFieldsValue({
        userGroup: value.toString(),
      });
    },
    // 过滤
    getFilter(sourceData, children) {
      let arr = [];
      if (sourceData) {
        sourceData.forEach((e, index) => {
          children.forEach((c, index) => {
            if (e.id == c.pid) {
              c.key = c.id;
              c.children = c.state === "closed" ? [] : "";
              if (e.children) e.children.push(c);
            } else {
              c.key = c.id;
            }
          });
          if (e.children) {
            // 子级有数据的时候 循环添加数据
            getFilter(e.children, children);
          }
        });
        arr = sourceData;
      }
      return arr;
    },
    handlePositionChange(value) {
      //   this.form.setFieldsValue({ userPosition: value.join(",") });
      this.form.setFieldsValue({ userPosition: value });
    },
  },
};
</script>
<style lang="less" scoped="scoped">
/deep/.userInfoSource-modal {
  .condition-warp {
    display: flex;
    margin-bottom: 20px;
    input {
      width: 220px;
      margin-right: 10px;
    }
    button {
      margin-left: 10px;
    }
  }
  .table-container {
    height: 400px;
    .vxe-table {
      thead {
        .vxe-header--row {
          .vxe-button {
            display: none;
          }
        }
      }
    }
  }
  .pager-container {
    flex-shrink: 0;
    box-sizing: border-box;
  }
}
.get-user-info-button {
  position: absolute;
  top: 10px;
  left: 170px;
}
.headText {
  font-size: 12px;
  color: red;
  position: absolute;
  top: 14px;
  left: 100px;
}

.userHeadPortraitBox {
  display: inline-flex;

  .ant-upload-picture-card-wrapper {
    flex: 1;
  }

  .userHeadPortraitText {
    flex: 2;
    font-size: 12px;
    color: red;
    line-height: 100px;
  }
}
</style>
